﻿using ServiceStack.Redis;

using ServiceStack.Text;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace XLB.ExtensionMethod.Redis
{
    /// <summary>
    /// redis帮助类
    /// </summary>
    public class RedisCacheHelper
    {
        private static readonly PooledRedisClientManager pool = null;
        private static readonly string[] redisHosts = null;

        /// <summary>
        /// redis连接地址
        /// </summary>
        public static string RedisHostStr = System.Configuration.ConfigurationManager.AppSettings["RedisHost"];

        /// <summary>
        /// 指定操作的redis数据库
        /// </summary>
        public static long RedisDb = Convert.ToInt64(System.Configuration.ConfigurationManager.AppSettings["RedisDb"]);

        /// <summary>
        /// Redis最大读取池
        /// </summary>
        public static int RedisMaxReadPool = 3;

        /// <summary>
        /// Redis最大写入池
        /// </summary>
        public static int RedisMaxWritePool = 1;

        static RedisCacheHelper()
        {
            var redisHostStr = string.IsNullOrEmpty(RedisHostStr) ? "127.0.0.1:6379" : RedisHostStr;

            if (!string.IsNullOrEmpty(redisHostStr))
            {
                redisHosts = redisHostStr.Split(',');

                if (redisHosts.Length > 0)
                {
                    RedisClientManagerConfig clientManagerConfig = new RedisClientManagerConfig();
                    clientManagerConfig.MaxWritePoolSize = RedisMaxWritePool;
                    clientManagerConfig.MaxReadPoolSize = RedisMaxReadPool;
                    clientManagerConfig.AutoStart = true;

                    pool = new PooledRedisClientManager(redisHosts, redisHosts, clientManagerConfig, RedisDb, null, null);
                }
            }
        }

        #region Add

        /// <summary>
        /// 添加缓存
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="key">key</param>
        /// <param name="value">value</param>
        /// <param name="expiry">到期时间</param>
        /// <param name="redisDb">指定数据库编码</param>
        public static void Add<T>(string key, T value, DateTime expiry,long redisDb= -1)
        {
            if (value == null)
            {
                return;
            }

            if (expiry <= DateTime.Now)
            {

                Remove(key);

                return;
            }

            try
            {
                if (pool != null)
                {
                    using (var r = pool.GetClient())
                    {
                        if (r != null)
                        {
                            r.SendTimeout = 1000;
                            if (redisDb<=-1)
                            {
                                r.Db = RedisDb;
                            }
                            else
                            {
                                r.Db = redisDb;
                            }
                            
                            r.Set(key, value, expiry - DateTime.Now);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                string msg = string.Format("{0}:{1}发生异常!{2}", "cache", "存储", key);
            }

        }

        /// <summary>
        /// 添加缓存
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="key">key</param>
        /// <param name="value">value</param>
        /// <param name="slidingExpiration">滑动到期时间</param>
        /// <param name="redisDb">指定数据库编码</param>
        public static void Add<T>(string key, T value, TimeSpan slidingExpiration,long redisDb=-1)
        {
            if (value == null)
            {
                return;
            }

            if (slidingExpiration.TotalSeconds <= 0)
            {
                Remove(key);

                return;
            }

            try
            {
                if (pool != null)
                {
                    using (var r = pool.GetClient())
                    {
                        if (r != null)
                        {
                            r.SendTimeout = 1000;
                            if (redisDb <= -1)
                            {
                                r.Db = RedisDb;
                            }
                            else
                            {
                                r.Db = redisDb;
                            }
                            r.Set(key, value, slidingExpiration);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                string msg = string.Format("{0}:{1}发生异常!{2}", "cache", "存储", key);
            }
        }

        /// <summary>
        /// 根据key获取redis缓存
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="key">key</param>
        /// <param name="redisDb">指定数据库编码</param>
        /// <returns></returns>
        public static T Get<T>(string key,long redisDb=-1)
        {
            if (string.IsNullOrEmpty(key))
            {
                return default(T);
            }

            T obj = default(T);

            try
            {
                if (pool != null)
                {
                    using (var r = pool.GetClient())
                    {
                        if (r != null)
                        {
                            r.SendTimeout = 1000;
                            if (redisDb <= -1)
                            {
                                r.Db = RedisDb;
                            }
                            else
                            {
                                r.Db = redisDb;
                            }
                            obj = r.Get<T>(key);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                string msg = string.Format("{0}:{1}发生异常!{2}", "cache", "获取", key);
            }


            return obj;
        }
        #endregion

        /// <summary>
        /// 移除指定redis缓存
        /// </summary>
        /// <param name="key">key</param>
        /// <param name="redisDb">指定数据库编码</param>
        public static void Remove(string key,long redisDb=-1)
        {
            try
            {
                if (pool != null)
                {
                    using (var r = pool.GetClient())
                    {
                        if (r != null)
                        {
                            r.SendTimeout = 1000;
                            if (redisDb <= -1)
                            {
                                r.Db = RedisDb;
                            }
                            else
                            {
                                r.Db = redisDb;
                            }
                            r.Remove(key);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                string msg = string.Format("{0}:{1}发生异常!{2}", "cache", "删除", key);
            }

        }

        /// <summary>
        /// 根据key判断是否存在
        /// </summary>
        /// <param name="key">key</param>
        /// <param name="redisDb">指定数据库编码</param>
        /// <returns></returns>
        public static bool Exists(string key,long redisDb=-1)
        {
            try
            {
                if (pool != null)
                {
                    using (var r = pool.GetClient())
                    {
                        if (r != null)
                        {
                            r.SendTimeout = 1000;
                            if (redisDb <= -1)
                            {
                                r.Db = RedisDb;
                            }
                            else
                            {
                                r.Db = redisDb;
                            }
                            return r.ContainsKey(key);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                string msg = string.Format("{0}:{1}发生异常!{2}", "cache", "是否存在", key);
            }

            return false;
        }
    }
}
